package com.dl.service.impl;

import com.dl.dao.StudentMapper;
import com.dl.pojo.Page;
import com.dl.pojo.Student;
import com.dl.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DL
 * @create 2021-03-23 14:24
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    @Transactional(readOnly = true)
    public int getTotal() {
        return studentMapper.getTotal();
    }

    @Override
    public boolean addStudent(Student student) {
        return studentMapper.addStudent(student) == 1;
    }

    @Override
    public boolean deleteStudent(int uid) {
        return studentMapper.deleteStudent(uid) == 1;
    }

    @Override
    public boolean updateStudent(Student student) {
        return studentMapper.updateStudent(student) == 1;
    }

    @Override
    @Transactional(readOnly = true)
    public Student queryStudentById(int uid) {
        return studentMapper.queryStudentById(uid);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Student> queryAllStudent() {
        return studentMapper.queryAllStudent();
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Student> queryStudentByLimit(int currentPage, int pageSize) {
        //map集合，保存分页基本信息
        Map<String, Integer> map = new HashMap<>();
        //分页对象，保存分页所有信息
        Page<Student> page = new Page<>();
        //设置数据总数
        page.setTotal(studentMapper.getTotal());
        //设置页面大小，同时计算页面总数
        page.setPageSize(pageSize);

        map.put("currentPage", (currentPage-1)*pageSize);
        map.put("pageSize", pageSize);

        //查询到的学生集合放入page对象中
        List<Student> students = studentMapper.queryStudentByLimit(map);
        page.setList(students);
        return page;
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Student> queryStudentByKey(String keyWord, int currentPage, int pageSize) {
        //map集合，保存分页基本信息
        Map<String, Object> map = new HashMap<>();
        //分页对象，保存分页所有信息
        Page<Student> page = new Page<>();

        int totalByKey = studentMapper.getTotalByKey(keyWord);
        if (totalByKey != 0){
            //设置数据总数
            page.setTotal(totalByKey);
            //设置页面大小，同时计算页面总数
            page.setPageSize(pageSize);

            map.put("keyWord", keyWord);
            map.put("currentPage", (currentPage-1)*pageSize);
            map.put("pageSize", pageSize);

            //查询到的学生集合放入page对象中
            List<Student> students = studentMapper.queryStudentByKey(map);
            page.setList(students);
            return page;
        }else {
            return null;
        }
    }
}
